package com.th.therp.service.Impl;

import com.th.therp.exception.BaseException;
import com.th.therp.mapper.CustomerMapper;
import com.th.therp.pojo.emtity.Customer;
import com.th.therp.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public List<Customer> list() {
        return customerMapper.list();
    }

    @Override
    public void add(Customer customer) {
        Customer existingCustomer = customerMapper.findByName(customer.getName());
        if (existingCustomer == null) {
            customerMapper.add(customer);
        }else {
            throw new BaseException("该客户已存在");
        }
    }

    @Override
    public void update(Customer customer) {
        Customer existingCustomer = customerMapper.findByName(customer.getName());
        if (existingCustomer != null && !existingCustomer.getId().equals(customer.getId())) {
            throw new BaseException("该客户已存在");
        }else {
            customerMapper.update(customer);
        }
    }

    @Override
    public void delete(List<Integer> ids) {
        ids.forEach(id -> {
            Customer customer = Customer.builder()
                    .id(id)
                    .isDeleted(1)
                    .build();
           customerMapper.update(customer);
        });
    }

    @Override
    public String findNameById(Integer customerId) {
        return customerMapper.findNameById(customerId);
    }
}